package cn.online.taxi.api.listen.controller;

import cn.online.taxi.common.constant.RedisKeyConstant;
import cn.online.taxi.common.jedis.JedisClient;
import cn.online.taxi.common.utils.LatNLongDistance;
import cn.online.taxi.common.utils.SpringUtil;
import cn.online.taxi.common.utils.StringUtil;
import cn.online.taxi.manager.dto.front.Order;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/orderSocket/{token}")
@Component
public class OrderSocketController {

    private static final Logger logger = LoggerFactory.getLogger(OrderSocketController.class);

    public static final Map<String, Session> sessionMap = new ConcurrentHashMap();

    private static int onlineCount = 0;
    private Session session;
    private String token;

    @OnOpen
    public void onOpen(@PathParam("token") String token, Session session) {
        this.token = token;
        this.session = session;

        addOnlineCount();
        sessionMap.put(token, session);
        logger.info(this.token + " 已连接");
        System.out.println("当前连接人数：" + getOnlineCount());
    }

    @OnClose
    public void onClose() {
        sessionMap.remove(token);
        logger.info(this.token + " 已关闭");
        subOnlineCount();
        System.out.println("当前连接人数：" + getOnlineCount());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        logger.info("收到消息：" + message);
        JSONObject jsonTo = JSONObject.parseObject(message);
        sendMessageTo(jsonTo.get("to").toString(), jsonTo.get("msg").toString());
    }

    public void sendMessageTo(String toUser, String message) throws IOException {

//        Object orderNumber = jsonTo.get("orderNumber");
//        Object identity = jsonTo.get("identity");

//        if (identity != null && identity.equals("passenger")) {
//            Object passengerLng = jsonTo.get("passengerLng");
//            Object passengerLat = jsonTo.get("passengerLat");
//
//        }
//        if (identity != null && identity.equals("driver")) {
//
//        }
        JSONObject data = JSON.parseObject(message);
        Set<Map.Entry<String, Session>> entries = sessionMap.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            String key = entry.getKey();
            if (StringUtil.isNotBlank(key) && key.equals(toUser)) {
                Session session = entry.getValue();
                if (session != null) {
                    JSONObject msgData = new JSONObject();
                    msgData.put("msg", data);
                    session.getAsyncRemote().sendText(msgData.toString());
                }
            }

        }

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        onlineCount--;
    }

}
